package com.example.service1.config.listener;

import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

@Component
public class ConfigChangeListener {

    @EventListener
    public void listen(EnvironmentChangeEvent event){
        if (event.getKeys().isEmpty()) {
            return;
        }
        System.out.println("=========配置数据发现变化=========");
        System.out.println(new Date(event.getTimestamp()));
        AnnotationConfigServletWebServerApplicationContext eventSource = (AnnotationConfigServletWebServerApplicationContext)event.getSource();
        Set<String> keys = event.getKeys();
        keys.forEach(key->{
            String updateProperty = eventSource.getEnvironment().getProperty(key);
            if(updateProperty==null){
                System.out.println("配置被刪除:"+key+":"+updateProperty);
                return;
            }
            System.out.println("最新键值对："+key+":"+updateProperty);
        });
        System.out.println("===============================");
    }

}
